 <template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="物料编码">
              <a-input placeholder="请输入物料编码" v-model="queryParam.materialCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="物料名称">
              <a-input placeholder="请输入物料名称" v-model="queryParam.materialName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="物料类型">
              <j-dict-select-tag
                placeholder="请选择物料类型"
                v-model="queryParam.materialType"
                dictCode="material_type"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="预警类型">
              <j-dict-select-tag
                placeholder="请选择预警类型"
                v-model="queryParam.warningType"
                dictCode="material_warning_type"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="是否处理">
              <a-select placeholder="请选择处理状态" v-model="queryParam.handled">
                <a-select-option :value="0">未处理</a-select-option>
                <a-select-option :value="1">已处理</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="预警日期">
              <j-date v-model="queryParam.createDate" placeholder="请选择日期" :showTime="false"></j-date>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="sync" @click="handleRefreshWarning">刷新预警</a-button>
      <a-button
        type="primary"
        icon="shopping-cart"
        @click="handleGeneratePurchase"
        v-if="hasPermission('wms:purchase:auto:generate')"
        >生成采购计划</a-button
      >
      <a-button type="primary" icon="download" @click="handleExport" v-if="hasPermission('wms:purchase:warning:export')"
        >导出</a-button
      >
    </div>

    <!-- 数据表格 -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
      >
        <!-- 预警类型列 -->
        <template slot="warningTypeSlot" slot-scope="text">
          <a-tag :color="text === 1 ? 'red' : 'orange'">
            <j-dict-tag :value="text" dictCode="material_warning_type" />
          </a-tag>
        </template>

        <!-- 库存状态列 -->
        <template slot="stockStatusSlot" slot-scope="text, record">
          <a-progress
            :percent="getStockPercent(record)"
            :status="getStockStatus(record)"
            size="small"
            :format="(percent) => `${record.currentQuantity}/${record.upperLimit}`"
          />
        </template>

        <!-- 处理状态列 -->
        <template slot="handledSlot" slot-scope="text">
          <a-badge :status="text ? 'success' : 'processing'" :text="text ? '已处理' : '未处理'" />
        </template>

        <!-- 操作列 -->
        <template slot="action" slot-scope="text, record">
          <a @click="handleMarkHandled(record)">标记已处理</a>
        </template>
      </a-table>
    </div>

    <!-- 物料详情模态框 -->
    <material-detail-modal ref="materialDetailModal"></material-detail-modal>

    <!-- 采购订单生成模态框 -->
    <purchase-order-modal ref="purchaseOrderModal" @ok="modalFormOk"></purchase-order-modal>
  </a-card>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JDictTag from '@/components/dict/JDictTag'
import JDate from '@/components/jeecg/JDate'
import MaterialDetailModal from '../material/modules/MaterialDetailModal'
import PurchaseOrderModal from './modules/PurchaseOrderModal'
import { USER_AUTH, SYS_BUTTON_AUTH } from '@/store/mutation-types'

export default {
  name: 'MaterialWarningList',
  mixins: [JeecgListMixin],
  components: {
    JDictSelectTag,
    JDictTag,
    JDate,
    MaterialDetailModal,
    PurchaseOrderModal,
  },
  data() {
    return {
      description: '物料预警管理页面',
      // 查询条件
      queryParam: {
        handled: 0, // 默认查询未处理的预警
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '物料编码',
          align: 'center',
          dataIndex: 'materialCode',
          width: 120,
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName',
          width: 120,
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'specification',
          width: 120,
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit',
          width: 80,
        },
        {
          title: '预警类型',
          align: 'center',
          dataIndex: 'warningType',
          width: 100,
          scopedSlots: { customRender: 'warningTypeSlot' },
        },
        {
          title: '库存状态',
          align: 'center',
          dataIndex: 'stockStatus',
          width: 150,
          scopedSlots: { customRender: 'stockStatusSlot' },
        },
        {
          title: '预警下限',
          align: 'center',
          dataIndex: 'lowerLimit',
          width: 100,
        },
        {
          title: '预警上限',
          align: 'center',
          dataIndex: 'upperLimit',
          width: 100,
        },
        {
          title: '建议采购量',
          align: 'center',
          dataIndex: 'suggestedPurchaseQuantity',
          width: 100,
          customRender: (text, record) => {
            return record.warningType === 1 ? (record.upperLimit - record.currentQuantity).toFixed(2) : 0
          },
        },
        {
          title: '处理状态',
          align: 'center',
          dataIndex: 'handled',
          width: 100,
          scopedSlots: { customRender: 'handledSlot' },
        },
        {
          title: '预警时间',
          align: 'center',
          dataIndex: 'createTime',
          width: 160,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 180,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/wms/purchase/warning/list',
        refresh: '/wms/purchase/warning/refresh',
        markHandled: '/wms/purchase/warning/markHandled',
        generatePurchase: '/wms/purchase/auto/generate',
        exportXlsUrl: '/wms/purchase/warning/exportXls',
      },
      dictOptions: {},
      permissionList: [],
    }
  },
  created() {
    // 初始化字典
    this.initDictConfig()

    // 加载权限数据
    this.loadPermissionData()

    // 页面加载时重置查询条件
    this.searchReset()
  },
  methods: {
    initDictConfig() {
      // 字典数据由JDictSelectTag和JDictTag组件自动加载，无需手动处理
    },

    // 加载权限数据
    loadPermissionData() {
      // 从sessionStorage获取权限
      let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || '[]')

      // 如果sessionStorage中没有权限，尝试从localStorage获取
      if (!authList || authList.length === 0) {
        authList = JSON.parse(localStorage.getItem(USER_AUTH) || '[]')
      }

      // 从按钮权限中获取
      const buttonAuth = JSON.parse(
        sessionStorage.getItem(SYS_BUTTON_AUTH) || localStorage.getItem(SYS_BUTTON_AUTH) || '[]'
      )

      // 合并权限
      if (buttonAuth && buttonAuth.length > 0) {
        authList = authList.concat(buttonAuth)
      }

      // 提取action字段
      this.permissionList = authList.map((auth) => auth.action || auth)
    },

    // 判断是否有权限
    hasPermission(permission) {
      if (!permission) return true // 如果未指定权限，默认有权限

      // 检查权限列表中是否包含指定权限
      if (this.permissionList.includes(permission)) {
        return true
      }

      // 检查权限列表中是否包含以逗号分隔的多个权限
      for (let perm of this.permissionList) {
        if (perm && perm.includes(',')) {
          const perms = perm.split(',')
          if (perms.includes(permission)) {
            return true
          }
        }
      }

      return false
    },

    getStockPercent(record) {
      // 计算库存百分比
      if (record.upperLimit <= 0) {
        return 0
      }

      // 计算当前库存占上限的百分比
      let percent = (record.currentQuantity / record.upperLimit) * 100

      // 限制在0-100之间
      percent = Math.min(100, Math.max(0, percent))

      return Math.round(percent)
    },

    getStockStatus(record) {
      // 根据预警类型获取进度条状态
      if (record.warningType === 1) {
        // 低于下限
        return 'exception'
      } else if (record.warningType === 2) {
        // 高于上限
        return 'warning'
      } else {
        return 'normal'
      }
    },

    // 刷新物料预警
    handleRefreshWarning() {
      this.$confirm({
        title: '确认刷新预警?',
        content: '刷新预警将重新检查所有物料库存状态，确定继续吗?',
        onOk: () => {
          this.loading = true
          postAction(this.url.refresh)
            .then((res) => {
              if (res.success) {
                this.$message.success('刷新预警成功')
                this.loadData()
              } else {
                this.$message.error(res.message || '刷新预警失败')
              }
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        },
      })
    },

    // 生成采购计划
    handleGeneratePurchase() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请选择至少一条物料预警记录')
        return
      }

      // 打开采购订单生成模态框
      this.$refs.purchaseOrderModal.show(null, this.selectedRowKeys)
    },

    // 生成单个物料的采购单
    handleGenerateSinglePurchase(record) {
      // 打开采购计划生成模态框
      this.$refs.purchasePlanModal.show([record.id])
    },

    // 查看物料详情
    handleViewMaterial(record) {
      this.$refs.materialDetailModal.show(record.materialCode)
    },

    // 标记物料预警为已处理
    handleMarkHandled(record) {
      this.$confirm({
        title: '确认标记已处理?',
        content: '标记为已处理后，该预警将不再显示在未处理列表中，确定继续吗?',
        onOk: () => {
          postAction(this.url.markHandled, { id: record.id }).then((res) => {
            if (res.success) {
              this.$message.success('标记已处理成功')
              this.loadData()
            } else {
              this.$message.error(res.message || '标记已处理失败')
            }
          })
        },
      })
    },

    // 查看关联采购单
    handleViewPurchase(record) {
      if (!record.purchaseOrderId) {
        this.$message.warning('该预警未关联采购单')
        return
      }

      // 跳转到采购单详情页
      this.$router.push({
        path: '/wms/purchase/detail',
        query: {
          id: record.purchaseOrderId,
        },
      })
    },
    handleExport() {
      this.handleExportXls('物料预警记录')
    },
  },
}
</script>

<style scoped>
@import '~@assets/less/common.less';
</style> 